<template>
  <div class="content">
    <el-form ref="form" :model="form" label-width="80px" :inline="true">
      <el-form-item>
        <el-input clearable v-model="form.name" size="mini" placeholder="请输入档口名称"></el-input>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="form.schoolId"
          @change="getShiTang"
          size="mini"
          clearable
          placeholder="请选择学校"
        >
          <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="form.shitangId" size="mini" clearable placeholder="请选择食堂">
          <el-option v-for="item in shitangList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-button size="mini" class="btn" @click="search(1)">清空</el-button>
      <el-button type="primary" size="mini" class="btn" @click="search(2)">
        <i class="fa fa-search" style="margin-right:5px;"></i>查询
      </el-button>
      <el-button
        @click="editAddOrUpdate(1)"
        type="primary"
        size="mini"
        class="btn"
        style="margin-right: 40px"
      >
        <i class="fa fa-plus" style="margin-right:5px;"></i>新增
      </el-button>
    </el-form>

    <!-- <el-divider></el-divider> -->

    <template>
      <el-table
        :data="tableData"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
        @expand-change="getClass"
        height="470"
        v-loading="loading"
        size="mini"
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="contentTable">
              <el-table
                :span-method="objectSpanMethod"
                :data="everyDK"
                height="400"
                v-loading="loading1"
                size="mini"
                style="width: 80%"
              >
                <el-table-column label="星期">
                  <template slot-scope="scope">
                    <span v-if="scope.row.weekday==1">星期一</span>
                    <span v-if="scope.row.weekday==2">星期二</span>
                    <span v-if="scope.row.weekday==3">星期三</span>
                    <span v-if="scope.row.weekday==4">星期四</span>
                    <span v-if="scope.row.weekday==5">星期五</span>
                    <span v-if="scope.row.weekday==6">星期六</span>
                    <span v-if="scope.row.weekday==7">星期天</span>
                  </template>
                </el-table-column>
                <el-table-column label="用餐时段">
                  <template slot-scope="scope">
                    <span v-if="scope.$index%3==0">早餐</span>
                    <span v-if="scope.$index%3==1">午餐</span>
                    <span v-if="scope.$index%3==2">晚餐</span>
                  </template>
                </el-table-column>
                <el-table-column label="学生价格（元）">
                  <template slot-scope="scope">
                    <span>{{scope.row.price}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="教师价格（元）">
                  <template slot-scope="scope">
                    <span>{{scope.row.discPrice}}</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="档口ID" prop="id"></el-table-column>
        <el-table-column label="档口名称" prop="name"></el-table-column>
        <el-table-column label="档口编号" prop="shopNo"></el-table-column>
        <el-table-column label="所属食堂" prop="marketName"></el-table-column>
        <el-table-column label="限制消费次数/天" prop="id">
          <template slot-scope="scope">
            <span>{{scope.row.limitCount==null?'不限制':scope.row.limitCount}}</span>
          </template>
        </el-table-column>
        <el-table-column label="限制消费金额/天" prop="id">
          <template slot-scope="scope">
            <span>{{scope.row.limitAmount==null?'不限制':scope.row.limitAmount}}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额设置" prop="id">
          <template slot-scope="scope">
            <el-switch @change="editPrice(scope.row.id,scope.row.isEditPrice)"
              v-model="scope.row.isEditPrice"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="210">
          <template slot-scope="scope">
            <el-button size="mini" @click="editAddOrUpdate(2,scope.row.id)">
              <i class="fa fa-edit" style="margin-right:5px;"></i>
              {{$t('action.edit')}}
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">
              <i class="fa fa-trash" style="margin-right:5px;"></i>
              {{$t('action.delete')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--    分页功能-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 15, 20,50,100]"
      :page-size="everyPageNum"
      layout="total, sizes,prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!--新增编辑弹框-->
    <el-dialog :title="updateStatus==1?'创建档口':'编辑档口'" :visible.sync="showEdit" width="60%" v-dialogDrag>
      <CanteenEdit @hideEdit="hideEditStatus" ref="child" :msg="updateStatus"></CanteenEdit>
    </el-dialog>
  </div>
</template>

<script>
import CanteenEdit from "@/components/BoothManagement/edit";
import Cookies from "js-cookie";

export default {
  name: "editCanteen",
  components: {
    CanteenEdit
  },
  data() {
    return {
      url: this.$Config.url,
      total: 1, //总页数
      updateStatus: 1, //默认是新增
      everyPageNum: 10, //每页多少条
      currentPage: 1, //当前页
      showEdit: false, //显示编辑弹框
      loading: false,
      loading1: false,
      form: {
        name: "",
        shitangId: "", //食堂id
        schoolId: "" //学校id
      },
      schoolList: [], //学校数据
      shitangList: [], //食堂数据
      tableData: [],
      expands: [],
      everyDK: [],
      expandedRows: "",
      getRowKeys(row) {
        return row.id;
      },
      tableData1: []
    };
  },
  mounted() {
    this.common();
    this.getSchool();
  },
  methods: {
    search(index) {
      if (index == 1) {
        this.form = {
          deviceNo: "",
          shitangId: "", //食堂id
          schoolId: "" //学校id
        };
      }
      this.common();
    },
    editPrice(id,isEditPrice){
      const that = this;
      if(isEditPrice){
        isEditPrice ='T'
      }else{
        isEditPrice ='F'
      }
      this.$axios
        .post(
          that.url + "/admin/shop/setEditPrice",
          that.$qs.stringify({ 'id':id,'isEditPrice': isEditPrice }),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.$message({
              type: "success",
              message: "提交成功!"
            });
            that.common(that.currentPage, that.everyPageNum);
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    getShiTang() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/market/list", {
          params: {
            deptId: that.form.schoolId
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.shitangList = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    getSchool() {
      const that = this;
      this.$axios
        .get(that.url + "/admin/dept/list", {
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          if (res.data.code == 200) {
            that.schoolList = res.data.data;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    getClass(row, expandedRows) {
      const that = this;
      that.gradeId = row.id;

      that.expandedRows = expandedRows;
      if (expandedRows.length) {
        that.expands = [];
        if (row) {
          that.expands.push(row.id); // 每次push进去的是每行的ID
        }
      } else {
        that.expands = []; // 默认不展开
      }

      that.everyClass();
    },
    everyClass() {

      const that = this;
      if(!that.gradeId){
        return;
      }
      that.loading1 = true;
      this.$axios
        .get(that.url + "/admin/shop/get/{id}", {
          params: {
            id: that.gradeId
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          that.loading1 = false;
          console.log(res)
          if (res.data.code == 200) {
            let data = [];
            data = res.data.data.mealDtos;
            let arr = [];
            data.forEach((item, index) => {
              for (let i = 0; i < 3; i++) {
                let obj = {};
                if (i == 0) {
                  obj["discPrice"] = item.breakfast.discPrice;
                  obj["price"] = item.breakfast.price;
                  obj["weekday"] = item.weekday;
                  arr.push(obj);
                  obj = {};
                } else if (i == 1) {
                  obj["discPrice"] = item.lunch.discPrice;
                  obj["price"] = item.lunch.price;
                  obj["weekday"] = item.weekday;
                  arr.push(obj);
                  obj = {};
                } else {
                  obj["discPrice"] = item.dinner.discPrice;
                  obj["price"] = item.dinner.price;
                  obj["weekday"] = item.weekday;
                  arr.push(obj);
                  obj = {};
                }
              }
            });
            that.everyDK = arr;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          that.loading1 = false;
          console.log(error);
        });
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex % 3 === 0) {
          return {
            rowspan: 3,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    handleDelete(index, row) {
      this.$confirm("您确认要删除该档口?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteStudent(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    deleteStudent(id) {
      const that = this;
      this.$axios
        .post(
          that.url + "/admin/shop/delete/{id}",
          that.$qs.stringify({ id }),
          {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          }
        )
        .then(function(res) {
          if (res.data.code == 200) {
            that.$message({
              type: "success",
              message: "删除成功!"
            });
            that.common(that.currentPage, that.everyPageNum);
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    common(pageNo = 1, pageSize = 10) {
      const that = this;
      this.loading = true;
      this.$axios
        .get(that.url + "/admin/shop/page", {
          params: {
            pageNo,
            pageSize,
            name: that.form.name,
            marketId: that.form.marketId
          },
          headers: {
            "x-baie-admin-token": Cookies.get("token")
          }
        })
        .then(function(res) {
          that.loading = false;
          if (res.data.code == 200) {
            let tableData = res.data.data.records;
            for(let i =0; i< tableData.length; i++){
              if(tableData[i].isEditPrice == 'T'){
                tableData[i].isEditPrice = true;
              }else{
                tableData[i].isEditPrice = false;
              }
            }
            that.tableData = tableData;

            that.total = res.data.data.total;
          } else {
            that.$message({
              message: res.data.msg,
              type: "warning"
            });
          }
        })
        .catch(function(error) {
          that.loading = false;
        });
    },
    handleClick(row) {
      console.log(row);
    },
    handleSizeChange(val) {
      //   每页多少条
      this.everyPageNum = val;
      this.common(this.currentPage, val);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.common(val, this.everyPageNum);
    },
    editAddOrUpdate(status, id) {
      //新增或编辑
      /**
       * 1是新增
       * 2是编辑
       */
      this.showEdit = true;
      if (status == 1) {
        //新增
        this.updateStatus = 1;
        setTimeout(() => {
          this.$refs["child"].resetForm("ruleForm");
        }, 0);
      } else {
        //编辑
        this.updateStatus = 2;
        setTimeout(() => {
          this.$refs["child"].resetData(id);
        }, 0);
      }
    },
    hideEditStatus(status) {
      this.showEdit = false;
      this.common(this.currentPage, this.everyPageNum);
      this.everyClass();
    }
  }
};
</script>

<style scoped lang="scss">
.contentTable {
  // height:400px;
  // overflow-y: scroll;
}
.el-pagination {
  float: right;
  margin: 20px 10px;
}

.table_btn {
  background: #eee;
  color: #7b9dda;
  border: none;
  outline: none;
  padding: 4px 10px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.button_list {
  margin-bottom: 10px;
}

.content {
  text-align: left;
}

.el-divider {
  margin: 10px 0;
}

.btn {
  margin-top: 7px;
}

.el-form-item {
  margin-bottom: 0;
}
</style>
